package com.minelx.datamicroscope.core.index;

import com.minelx.datamicroscope.core.condition.RawCondition;
import com.minelx.datamicroscope.core.query.AliasedKey;
import com.minelx.datamicroscope.core.query.CollectingResource;
import io.gitee.minelx.filesystem.File;

import java.util.List;

class AutoDeterminingIndexFactory implements IndexFactory {
	private final List<ConditionalIndexFactory> indexFactories;

	AutoDeterminingIndexFactory(List<ConditionalIndexFactory> indexFactories) {
		this.indexFactories = indexFactories;
	}

	@Override
	public Index createIndex(List<AliasedKey> remainingKeys, List<RawCondition> conditions, CollectingResource collectingResource, File destination) {
		String repositoryTablePath = collectingResource.firstCollectedField().commonTable().path();
		return indexFactories.stream()
				.filter(which -> which.available(repositoryTablePath))
				.findFirst().orElseThrow(() -> new UnsupportedOperationException("no index factory available for table: " + repositoryTablePath))
				// create from available index factory
				.createIndex(remainingKeys, conditions, collectingResource, destination);
	}
}
